package com.example.lotterysystem.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisUtil {

    private final static Logger logger= LoggerFactory.getLogger(RegexUtil.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 往redis存数据
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,String value){
        try {
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            logger.error("set error ,set({},{})",key,value,e);
            return false;
        }
    }

    /**
     * 存储数据时设置一个过期时间
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key,String value,Long time){
        try {
            stringRedisTemplate.opsForValue().set(key, value,time, TimeUnit.SECONDS);
            return true;
        }catch (Exception e){
            logger.error("set error ,set({},{},{})",key,value,time,e);
            return false;
        }
    }

    /**
     * 从redis数据获取
     * @param key
     * @return
     */
    public String get(String key){
        try {
            if (key!=null && StringUtils.hasText(key)){
                return stringRedisTemplate.opsForValue().get(key);
            }else {
                return null;
            }
        }catch (Exception e){
            logger.error("get error,get({})",key,e);
            return null;
        }
    }

    /**
     * 删除value
     * @param key
     * @return
     */
    public boolean delete(String... key){
        try {
            if(key!=null&&key.length>0){
                if (key.length==1){
                    stringRedisTemplate.delete(key[0]);
                }else {
                    stringRedisTemplate.delete(
                            (Collection<String>) CollectionUtils.arrayToList(key)
                    );
                }
            }
            return true;
        }catch (Exception e){
            logger.error("delete error,delete({})",key,e);
            return false;
        }
    }

    /**
     * 查询是否存在指定key
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        try {
            return StringUtils.hasText(key)
                    ?stringRedisTemplate.hasKey(key)
                    :false;
        }catch (Exception e){
            logger.error("hasKey error,hasKey({})",key,e);
            return false;
        }
    }

}
